package cn.hxh.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: HongXiaoHan
 * @Description
 * @Date: 2020/8/20 11:44
 */


//保存用户上一次访问的时间
public class CookieServlet01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        String format = s.format(new Date());
        //搜索是否存在该cookie
        Cookie[] cookies = req.getCookies();
        //标志
        boolean flag = false;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("time")) {
                    flag = true;
                    break;
                }
                if (!cookie.getName().equals("time")) {
                    flag = false;
                }
            }
        }

        //存在time  cookie
        if (flag){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("time")) {
                    //取cookie
                    String value = cookie.getValue();
                    //重置cookie
                    cookie.setValue(format);
                    //设置一天有效期
                    cookie.setMaxAge(60 * 60 * 24);
                    resp.addCookie(cookie);
                    req.setAttribute("time","你上次的访问时间:"+value);
                    break;
                }
            }
        }
        if (!flag){
            //第一次如果没有   就进行cookie存储
            Cookie cookie = new Cookie("time", format);
            //设置一天有效期
            cookie.setMaxAge(60 * 60 * 24);
            resp.addCookie(cookie);
            req.setAttribute("time", "欢迎您的访问");
        }
        req.getRequestDispatcher("time.jsp").forward(req, resp);

    }
}
